import React, { Component } from 'react';
import Taro, { Config, getCurrentInstance } from '@tarojs/taro';
import { View, Image } from '@tarojs/components'
import GoodList from '@/components/GoodsView/GoodList'
import MoreView from '@/components/GoodsView/MoreView'
import StateList from '@/components/StateList'
import { staticUrl } from '@/utils'
import { AtSteps } from 'taro-ui'
import dayjs from 'dayjs'
import { getOrderDetails, cancelRefund, viewRefund } from '@/api/order'
import './index.scss'

type State = {
  details: any
  refundDeatail: any
  down: boolean
  step: number
  stepStatus: any
}
const bar3 = staticUrl('/img/order/bar3.png')
// const shalou = staticUrl('/img/order/icon-shalou.png')
export default class Index extends Component {
  $instance = getCurrentInstance();
  constructor() {
      super(...arguments)
      this.state = {
        details: {},
        refundDeatail: null,
        down: false,
        step: 0,
        stepStatus: [{
          title: '提交申请',
          status: 'success'
        }, {
          title: '商家审核',
        }, {
          title: '系统退款'
        }]
      }
    }

  state: State
  UNSAFE_componentWillMount() { }
  async componentDidMount() {
    let { orderNumber, refundApplyNumber } = this.$instance.router.params
    Taro.showLoading({ title: '加载中' })
    await Promise.all([this.getOrderDetails(orderNumber), this.getOrderRefundDetail(refundApplyNumber)])
    Taro.hideLoading()
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  async getOrderDetails(orderNumber) {
    try {
      let res = await getOrderDetails({ orderNumber })
      if (!res.data.success) throw Error()
      const { data } = res.data
      this.setState({
        details: data
      })
    } catch (error) {

    }
  }

  async getOrderRefundDetail(refundApplyNumber) {
    try {
      let res = await viewRefund({ refundApplyNumber })
      if (!res.data.success) throw Error()
      let { data } = res.data
      let { stepStatus } = this.state
      let { status, storeIsAgree, financeIsAgree } = data
      if (+storeIsAgree === 1 || +financeIsAgree === 1) {
        stepStatus[1].status = 'success'
      }
      // 3:退款成功
      if (+status === 3) {
        stepStatus[1].status = 'success'
        stepStatus[2].status = 'success'
      }
      // 4:退款失败
      if (+status === 4) {
        stepStatus[1].status = 'error'
        stepStatus[2].status = 'error'
      }
      // 5:取消退款
      if (+status === 5) {
        stepStatus[1].status = 'error'
        if (+storeIsAgree === 1 || +financeIsAgree === 1) {
          stepStatus[1].status = 'success'
        }
        stepStatus[2].status = 'error'
      }
      this.setState({
        refundDeatail: data,
        stepStatus
      })
    } catch (error) {
    }
  }

  changeGoodsStatus(e) {
      this.setState({
          down: e
      })
  }
  changeStep() {}
  async cancelRefund() {
    Taro.showLoading({
      title: '取消中..'
    })
    try {
      let { refundApplyNumber } = this.$instance.router.params
      let res = await cancelRefund({ refundApplyNumber })
      if (!res.data.success) throw Error()
      Taro.navigateBack()
    } catch (error) {
      Taro.showToast({
        icon: 'none',
        title: '取消申请失败，请稍后重试'
      })
    }
  }
  render() {
    const { details, refundDeatail, down, stepStatus } = this.state
    let cartList: any = null
    const detailsLoaded = Object.keys(details).length ? true : false
    if (detailsLoaded) {
      cartList = details.items && (Object.keys(details.items).length && details.items.goods) ? details.items.goods : null
      if (!down && cartList) {
          if (cartList.length > 3) {
              cartList = cartList.slice(0, 3)
          }
      }
    }

    // console.log(cartList, details)
    return detailsLoaded && refundDeatail && <View className='order-details'>
      <View className='bar-wrap'>
        <Image className='bar' src={bar3}></Image>
        <View className='status-row'>
            <View className='status'>
                {/* <Image className='shalou' src={shalou}></Image> */}
                {refundDeatail.statusLabel}
            </View>
        </View>
      </View>
      <View className='progree-view'>
        <AtSteps
          items={stepStatus}
          current={this.state.step}
          onChange={this.changeStep.bind(this)}
        />
      </View>
      {
          cartList && <View className='goods-item margin-top20'>
              {
                  details.type == 1 &&  (
                      <View className='annual-name'>
                          <View className='goods-name'>{details.annualCardDetail.annualCardName}</View>
                          <View className='vailday'>
                              <View className='span'>{details.annualCardDetail.validDay}天</View>
                              <View className='tips'>有效期</View>
                          </View>
                      </View>
                  )
              }
              {
                  cartList.map((v, index) => {
                      return <View key={v.id} className='li'><GoodList list={v} /></View>
                  })
              }
              {
                  details.items.goods.length > 3 && <MoreView handle={this.changeGoodsStatus.bind(this)} />
              }
          </View>
      }
      <View className='margin-top20'>
        <StateList name='订单号' context={details.orderNumber} />
        <StateList name='申请单号' context={refundDeatail.refundApplyNumber} />
        <StateList name='申请时间' context={dayjs.unix(refundDeatail.refundTime).format('YYYY-MM-DD HH:mm:ss') } />
				{/*  */}
        <StateList name='服务类型' context='退款' />
        <StateList name='申请原因' context={refundDeatail.reason} />
        <StateList name='退款方式' context={refundDeatail.refundMethodLabel} />
				<StateList name='退款金额' contextColor ="#f00"context={refundDeatail.refundPrice} />
      </View>
			{
				refundDeatail.mobile ?  <View className='margin-top20'>
        <StateList name='退款联系人' context={refundDeatail.linkman} />
        <StateList name='联系方式' context={`￥${refundDeatail.mobile}`} />
      </View> : null
			}

      {
        details.action && Number(details.action.isCouldCancelRefund) === 1 &&
        <View className='bt-handle'>
          <View onClick={() => this.cancelRefund()} className='btn'>取消申请</View>
        </View>
      }
    </View>
  }
}
